import { useStore } from '@/hooks';
import { Button, Dialog, Form, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { TitleGrid, column } from '../../stores/definitions_refund';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import moment from 'moment';
import OrderRefund from './OrderRefund';
import { areArraysEqual, arrayContrast, computePrice } from '../../stores/method';

const tableId = uniqueId('tauTable-');

function RefundRecord({ orderId, onCancel }) {
  const { ccOrderStore: store } = useStore();
  const [orderDetails, setOrderDetails] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  const [modal, setModal] = useState([]);
  const orderRef = useRef();

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (JSON.stringify(orderId) !== '{}') {
        const orderInfo = await store.getIdRefund(orderId);
        setOrderDetails([...orderInfo]);
        editCtx.origin = _.cloneDeep(orderInfo);
        _.assign(orderRefund, orderInfo);
      }
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    if (name === 'refundTime') {
      const diff = moment.duration(moment(orderRefund.busOrder.shift.date).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟${diff.seconds()}秒`;
      _.assign(orderRefund, { distanceTime: diffStr });
    }
    _.set(orderRefund, name, value);

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  // 新增订单数据提交
  const handleOnRefund = async (result, state, type) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        // eslint-disable-next-line no-shadow
        const { id, refundTime, refundPrice, distanceTime, refundRemark = '', orderDetails, attachments } = toJS(result);
        const utcTime = moment.utc(refundTime).toISOString();
        if (store._orderRefundStatus === '0') {
          const orderTicket = orderDetails?.filter((item) => item.check && !item.disabled);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice,
            distanceTime,
            refundRemark,
            attachments: attachments || [],
            ticketRefundInfos: orderTicket,
            state,
            type,
          };
        } else {
          refundArgs = {
            cancelTime: utcTime,
            refundPrice,
            distanceTime,
            refundRemark,
            attachments: attachments || [],
            state,
            type,
          };
        }
        await store.orderSponsorRefund(id, refundArgs);
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
    // eslint-disable-next-line require-atomic-updates
    store._orderStatus = '0';
    await init();
  };

  const handleCancelRefund = (refund) => {
    Dialog.confirm({
      content: t`是否取消该退款申请`,
      onOk: () => cancelRefund(refund),
    });
  };

  async function cancelRefund(refund) {
    await store.orderCancelRefund(refund);
    await init();
  }

  async function init() {
    const orderInfo = await store.getIdRefund(orderId);
    setOrderDetails([...orderInfo]);
  }

  const handleCommitRefund = (refund) => {
    const prices = computePrice(refund);
    const { otherPrice, platformPrice } = prices;
    Dialog.confirm({
      title: t`是否提交该退款申请`,
      content: (
        <div>
          {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
          <br />
          {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
        </div>),
      onOk: () => commitRefund(refund),
    });
  };

  async function commitRefund(refund) {
    try {
      await store.orderCommitRefund(refund);
      Message.success({ content: t`提交成功` });
      await init();
    } catch (e) {
      Message.error({ content: t`提交失败`, duration: 7000 });
      throw e;
    }
  }

  const handleOpenEdit = (result) => {
    orderRef.current = result;
    setModal(['refund']);
  };

  const handleRefundCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => handleCancel1?.(),
      });
      return;
    }
    handleCancel1?.();
  };

  // Modal窗口关闭回调
  const handleCancel1 = () => {
    setModal([]);
  };

  // 车票二次编辑
  const handleEdit = async (result, refundState, abState, A, B, open, account) => {
    if (!_.isEmpty(result)) {
      try {
        let argsEdit;
        if (refundState === '0') {
          if (abState === '0') {
            const numberAccount = A.map((item) => ({
              ...item,
              contributionAmount: Number(item.contributionAmount),
            }));
            const equal = areArraysEqual(store.initAccounts, numberAccount);
            const computeAccount = arrayContrast(open, account, A);
            argsEdit = {
              ...toJS(result),
              cancelTime: moment.utc(result.cancelTime).subtract(8, 'hours').toISOString(),
            };
            if (!equal) {
              argsEdit.refundPayers = computeAccount;
            }
          } else {
            const { cancelRemarkB, refundPriceB, serviceChargeB, cancelTimeB } = result;
            const numberAccount = B.map((item) => ({
              ...item,
              contributionAmount: Number(item.contributionAmount),
            }));
            const equal = areArraysEqual(store.initAccounts, numberAccount);
            const computeAccount = arrayContrast(open, account, B);
            argsEdit = {
              ...toJS(result),
              cancelTime: moment.utc(cancelTimeB).subtract(8, 'hours').toISOString(),
              cancelRemark: cancelRemarkB,
              refundPrice: refundPriceB,
              serviceCharge: serviceChargeB,
            };
            if (!equal) {
              argsEdit.refundPayers = computeAccount;
            }
          }
        } else {
          argsEdit = {
            ...toJS(result),
            cancelTime: moment.utc(result.cancelTime).subtract(8, 'hours').toISOString(),
          };
        }
        await store.orderRefundUpdate(argsEdit);
        Message.success({ content: t`修改退款信息成功` });
      } catch (e) {
        Message.error({ content: t`修改退款信息失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
    await init();
  };

  return (
    <Form
      inline
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`申请退款记录`} />
      <div className="content">
        <TauTable
          instanceId={tableId}
          // primaryKey="ticketCode"
          tableLayout="fixed"
          dataSource={orderDetails}
          rowKey="applicationId" // 设置每行的唯一标识
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
            column('applicationId', { width: 160 }),
            column('type', {}),
            column('state', {}),
            column('cancelTime', { width: 180 }),
            column('refundTime', { width: 180 }),
            column('refundPrice', {
              width: 188,
              title: t`订单退款金额/第三方金额`,
              cell: (v, i, r) => {
                const { refundInfos = [] } = r;
                const douyin = refundInfos.filter((p) => p.refundChannel !== 'WX');
                const price = douyin.reduce((acc, item) => {
                  const { refundPrice = 0 } = item;
                  acc += refundPrice;
                  return acc;
                }, 0);
                return <span>{`${v.toFixed(2)} / ${price.toFixed(2)}`}</span>;
              },
            }),
            column('cancelRemark', { width: 180 }),
            {
              title: t`操作`,
              width: 200,
              cell: (_, __, refund) => (
                <>
                  <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleOpenEdit(refund)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleCancelRefund(refund)} >{t`取消`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleCommitRefund(refund)} >{t`提交申请退款`}</Button>
                </>
              ),
            },
          ]}
        />
      </div>

      <Drawer
        visible={modal[0] === 'refund'}
        title={t`编辑申请退票退款`}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
          store._orderStatus = '0';
        }}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '70%' }}
        width="90%"
      >
        <OrderRefund
          modal={modal}
          order={orderRef.current}
          onCancel={handleRefundCancel}
          onSubmit={handleOnRefund}
          onEdit={handleEdit}
          isEdit={1}
        />
      </Drawer>
    </Form>
  );
}


export default observer(RefundRecord);

